package com.jinyang.jetpackdemo.util.http.interceptor

import android.content.Context
import com.jinyang.jetpackdemo.util.NetUtil
import kotlin.Throws
import okhttp3.CacheControl
import okhttp3.Interceptor
import okhttp3.Response
import java.io.IOException

/**
 * @Author: LiuJinYang
 * @CreateDate: 2020/5/20
 * 缓存拦截器
 */
class CacheInterceptor(private val mContext: Context) : Interceptor {
    // 有网络时 设置缓存超时时间1个小时
    var maxAge = 0

    // 无网络时，设置超时为1个月
    var maxStale = 60 * 60 * 24 * 30
    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        var request = chain.request()
        if (!NetUtil.isNetworkAvailable(mContext)) {
            request = request.newBuilder()
                .cacheControl(CacheControl.FORCE_CACHE)
                .build()
        }
        val response = chain.proceed(request)
        if (NetUtil.isNetworkAvailable(mContext)) {
            response.newBuilder()
                .removeHeader("Pragma")
                .header("Cache-Control", "public, max-age=$maxAge")
                .build()
        } else {
            response.newBuilder()
                .removeHeader("Pragma")
                .header("Cache-Control", "public, only-if-cached, max-stale=$maxStale")
                .build()
        }
        return response
    }
}